const events = require("events");
const {exec, spawn} = require('child_process');

const MBI_EVENTS = {
    CONNECTED:'connected',
}
const REGEX = {
    TRID : /TRID:'\d'/,
    RX_PACKAGES : /^rx_packets=(\d*)/,
    TX_PACKAGES : /^tx_packets=(\d*)/,
    RX_BYTES : /^rx_bytes=(\d*)/,
    TX_BYTES : /^tx_bytes=(\d*)/,
    CONN_TIME: /^connected_time=(\d*)/,
    SIGNAL:/signal=(-*\d*)/,
    LINESPLITE : /[\r\n]/
}
class MbiNetworkParser extends events.EventEmitter {

    constructor(){
        super();
    }

    connect(){
        //const stationParse = new StationParser();
        //抛到上一层事件
        //stationParse.on(EVENTS.FIND_STA,(sta)=>{this.emit(EVENTS.FIND_STA,sta)});

        this.run('mbim-network',['/dev/cdc-wdm0','start'],{
            onData : (data)=>{
                stationParse.parse(data.toString());
            },
            onClose : (code,data)=>{
                if (code !== 0){
                    console.log('program exit with error. code:${code}');
                }
            },
        })
    }

    queryconnectStatus(){
        this.run('mbimcli.bat',['--query-radio-state','--no-close'],{
            onData : (data)=>{
                console.log(data.toString());
            },
            onClose : (code,data)=>{
                if (code !== 0){
                    console.log('program exit with error. code:${code}');
                }
            },
        })
    }

    run(cmd,params,{onData,onError,onClose}){

        //let result = fs.readFileSync('./test.txt',{encoding :'utf8'});
        //onData(result);
        //return;
        const hostapd_cli = spawn(cmd,params,{detached : false});
        hostapd_cli.stdout.on('data', (data) => {
          onData && onData(data);
        });
        
        hostapd_cli.stderr.on("data",(data)=>{
           onError && onError(data);
        });
        
        hostapd_cli.on("close",(code,signal) =>{
           onClose && onClose(code,signal);
        });
    }    
}

class MbiNetwork extends events.EventEmitter{
    constructor(){
        super();
        this.interval = null;
        this.mbinetworkParser = new MbiNetworkParser();
        this.mbinetworkParser.on(MBI_EVENTS.CONNECTED,(sta)=>{
            this.emit(MBI_EVENTS.CONNECTED,sta);
        });
    }
    _parseCmd(param){
        param && param.mbinetworkParser.queryconnectStatus();
    }

    start(){
        this.interval = setInterval(this._parseCmd,1000,this);
    }
    stop(){
        clearInterval(this.interval);
    }
}

module.exports = { MbiNetwork,MBI_EVENTS};
